package com.ydj.manager;

import org.hibernate.annotations.common.util.impl.LoggerFactory;
import org.jboss.logging.Logger;

import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadPoolExecutorWarp extends ThreadPoolExecutor {
    private static Logger logger = LoggerFactory.logger(ThreadPoolManager.class);

    private ArrayList<Runnable> runningTaskArray;
    private final static byte[] runningTaskArrayLock = new byte[0];

    ThreadPoolExecutorWarp(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(maximumPoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        runningTaskArray = new ArrayList<>();
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        synchronized (runningTaskArrayLock) {
            runningTaskArray.add(r);
        }
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        synchronized (runningTaskArrayLock) {
            runningTaskArray.remove(r);
        }
    }

    public void printInfo() {
        StringBuilder sb = new StringBuilder();
        synchronized (runningTaskArrayLock) {
            for (Runnable runnable : runningTaskArray) {
                if (runnable != null) {
                    sb.append(runnable.toString()).append(", ");
                }
            }
        }
        if (sb.length() > 0) {
            logger.info("当前线程是:" + sb.toString());
        }
    }
}
